package jpa4azure.impl;

import java.util.Date;

import jpa4azure.type.FieldContext;
import jpa4azure.type.Key;
import jpa4azure.type.TypeWrapper;
import jpa4azure.type.TypeWrapperFactory;

import com.windowsazure.samples.Property;
import com.windowsazure.samples.PropertyCollection;
import com.windowsazure.samples.table.AzureTableManager;

public class UpdateOperation {

	AzureTableManager client;
	
	public UpdateOperation(AzureTableManager client) {
		this.client = client;
	}

	public void save(Object entity) throws Exception {
		Class c = entity.getClass().getSuperclass();
		TypeWrapper type =  TypeWrapperFactory.wrap(c);
		Key key = type.id(entity);
		
		PropertyCollection props = new PropertyCollection(key.getPartition(), key.getRow());
		for (FieldContext f : type.getDirtyFields((Persistable)entity))
			f.getCloudTableColumn(props);	
	    Property<?> typeProp = Property.newProperty("jpa4azureBeanType", type.getWrappedType().getName());
		props.add(typeProp);
		client.mergeEntity("", new Date(), "jpa4azure", type.getTableName(), props, null);
	}

}
